<?php

namespace Bootstrap;

class ClassAutoLoader
{
    protected static $rootPath = array();

    protected static $loader;

    private function __construct()
    {
        self::$rootPath = array(
            // 项目根路径
            __DIR__ . '/../',
            // 依赖包路径
            __DIR__ . '/../Vendor/'
        );
    }

    public static function instance()
    {
        if (null == static::$loader) {
            static::$loader = new static();
        }
        return static::$loader;
    }

    public function loader($class)
    {
        $name = str_replace('\\', DIRECTORY_SEPARATOR, $class);

        foreach (static::$rootPath as $path) {
            $file = $path . $name . '.php';
            if (is_file($file)) {
                require_once $file;
                if (class_exists($name)) {
                    return true;
                }
            }
        }
        return false;
    }

    public function init()
    {
        spl_autoload_register(array($this, 'loader'));
        return $this;
    }
}
